/**
 * 医疗AI知识库
 * 包含医疗知识、诊疗指南、药物信息、症状分析等专业医疗内容
 */

'use client'

// 症状信息接口
export interface SymptomInfo {
  name: string
  description: string
  commonCauses: string[]
  recommendedDepartments: string[]
  urgencyLevel: 'low' | 'medium' | 'high' | 'critical'
  selfCareAdvice: string[]
  whenToSeekHelp: string[]
  relatedSymptoms: string[]
  diagnosticTests: string[]
}

// 药物信息接口
export interface MedicationInfo {
  name: string
  genericName: string
  category: string
  description: string
  indications: string[]
  contraindications: string[]
  sideEffects: string[]
  dosageInstructions: string
  interactions: string[]
  precautions: string[]
  pregnancyCategory?: string
}

// 疾病信息接口
export interface DiseaseInfo {
  name: string
  icdCode?: string
  description: string
  symptoms: string[]
  causes: string[]
  riskFactors: string[]
  diagnosis: string[]
  treatment: string[]
  prevention: string[]
  prognosis: string
  relatedDiseases: string[]
}

// 检查项目信息接口
export interface DiagnosticTest {
  name: string
  type: 'blood' | 'imaging' | 'biopsy' | 'physical' | 'other'
  description: string
  indications: string[]
  preparation: string[]
  procedure: string
  normalRanges?: Record<string, string>
  interpretation: string[]
  risks: string[]
  cost?: number
}

// 科室专科信息接口
export interface DepartmentSpecialty {
  name: string
  description: string
  commonConditions: string[]
  procedures: string[]
  specialists: string[]
  equipment: string[]
  whenToVisit: string[]
  preparationTips: string[]
}

class MedicalKnowledge {
  private symptoms: Map<string, SymptomInfo> = new Map()
  private medications: Map<string, MedicationInfo> = new Map()
  private diseases: Map<string, DiseaseInfo> = new Map()
  private diagnosticTests: Map<string, DiagnosticTest> = new Map()
  private departments: Map<string, DepartmentSpecialty> = new Map()
  private emergencyKeywords: Set<string> = new Set()

  constructor() {
    this.initializeKnowledgeBase()
  }

  /**
   * 初始化医疗知识库
   */
  private initializeKnowledgeBase() {
    this.loadSymptoms()
    this.loadMedications()
    this.loadDiseases()
    this.loadDiagnosticTests()
    this.loadDepartments()
    this.loadEmergencyKeywords()
  }

  /**
   * 加载症状信息
   */
  private loadSymptoms() {
    const symptomsData: SymptomInfo[] = [
      {
        name: '头痛',
        description: '头部疼痛或不适感，可能是紧张性、偏头痛、或其他原因引起',
        commonCauses: ['紧张', '压力', '偏头痛', '高血压', '脑部疾病', '感染'],
        recommendedDepartments: ['神经内科', '内科', '急诊科'],
        urgencyLevel: 'medium',
        selfCareAdvice: ['充分休息', '保持水分', '避免强光', '放松技巧', '规律作息'],
        whenToSeekHelp: ['剧烈头痛', '伴有发热', '视力模糊', '恶心呕吐', '意识改变'],
        relatedSymptoms: ['恶心', '呕吐', '视力模糊', '颈项强直'],
        diagnosticTests: ['头颅CT', '头颅MRI', '血压测量', '血常规']
      },
      {
        name: '胸痛',
        description: '胸部区域的疼痛或不适，可能涉及心脏、肺部或其他器官',
        commonCauses: ['心绞痛', '心肌梗死', '肺栓塞', '胃食管反流', '肌肉拉伤'],
        recommendedDepartments: ['心内科', '急诊科', '呼吸内科'],
        urgencyLevel: 'critical',
        selfCareAdvice: ['立即休息', '避免剧烈活动', '保持冷静'],
        whenToSeekHelp: ['剧烈胸痛', '呼吸困难', '出汗', '恶心', '左臂疼痛'],
        relatedSymptoms: ['呼吸困难', '心悸', '出汗', '恶心'],
        diagnosticTests: ['心电图', '心肌酶', '胸部X光', '心脏彩超']
      },
      {
        name: '发热',
        description: '体温超过正常范围，通常指口温超过37.5°C',
        commonCauses: ['细菌感染', '病毒感染', '免疫反应', '肿瘤', '药物反应'],
        recommendedDepartments: ['内科', '急诊科', '感染科'],
        urgencyLevel: 'medium',
        selfCareAdvice: ['多喝水', '适当休息', '物理降温', '避免过度包裹'],
        whenToSeekHelp: ['高热不退', '伴有皮疹', '呼吸困难', '意识模糊', '婴幼儿发热'],
        relatedSymptoms: ['寒战', '头痛', '肌肉酸痛', '乏力'],
        diagnosticTests: ['血常规', '血培养', '尿常规', '胸部X光']
      },
      {
        name: '腹痛',
        description: '腹部区域的疼痛，可能涉及多个器官系统',
        commonCauses: ['胃炎', '阑尾炎', '胆囊炎', '肠梗阻', '泌尿系结石'],
        recommendedDepartments: ['消化内科', '普外科', '急诊科'],
        urgencyLevel: 'high',
        selfCareAdvice: ['避免进食', '保持舒适体位', '热敷可能有帮助'],
        whenToSeekHelp: ['剧烈腹痛', '伴有呕吐', '腹肌紧张', '发热', '血便'],
        relatedSymptoms: ['恶心', '呕吐', '腹泻', '便血'],
        diagnosticTests: ['腹部CT', '腹部超声', '血常规', '肝功能']
      }
    ]

    symptomsData.forEach(symptom => {
      this.symptoms.set(symptom.name, symptom)
    })
  }

  /**
   * 加载药物信息
   */
  private loadMedications() {
    const medicationsData: MedicationInfo[] = [
      {
        name: '阿司匹林',
        genericName: 'Aspirin',
        category: '解热镇痛药',
        description: '非甾体抗炎药，具有解热、镇痛、抗炎和抗血小板聚集作用',
        indications: ['发热', '疼痛', '心血管疾病预防', '关节炎'],
        contraindications: ['胃溃疡', '出血倾向', '哮喘', '肝肾功能不全'],
        sideEffects: ['胃肠不适', '出血', '过敏反应', '肝肾损害'],
        dosageInstructions: '成人：0.3-0.6g，每日3-4次，饭后服用',
        interactions: ['华法林', '甲氨蝶呤', 'ACE抑制剂'],
        precautions: ['餐后服用', '定期监测肝肾功能', '避免与酒精同服'],
        pregnancyCategory: 'C'
      },
      {
        name: '头孢克洛',
        genericName: 'Cefaclor',
        category: '抗生素',
        description: '第二代头孢菌素类抗生素，广谱抗菌',
        indications: ['呼吸道感染', '泌尿道感染', '皮肤软组织感染'],
        contraindications: ['青霉素过敏史', '头孢菌素过敏史'],
        sideEffects: ['过敏反应', '胃肠反应', '二重感染'],
        dosageInstructions: '成人：250-500mg，每日3次',
        interactions: ['华法林', '丙磺舒'],
        precautions: ['过敏试验', '完成疗程', '监测肝肾功能'],
        pregnancyCategory: 'B'
      }
    ]

    medicationsData.forEach(medication => {
      this.medications.set(medication.name, medication)
      // 同时存储通用名
      this.medications.set(medication.genericName.toLowerCase(), medication)
    })
  }

  /**
   * 加载疾病信息
   */
  private loadDiseases() {
    const diseasesData: DiseaseInfo[] = [
      {
        name: '高血压',
        icdCode: 'I10',
        description: '以动脉血压持续升高为主要特征的慢性疾病',
        symptoms: ['头痛', '头晕', '心悸', '乏力', '视力模糊'],
        causes: ['遗传因素', '环境因素', '生活方式', '其他疾病'],
        riskFactors: ['年龄', '家族史', '肥胖', '吸烟', '高盐饮食', '缺乏运动'],
        diagnosis: ['血压测量', '24小时动态血压监测', '心电图', '眼底检查'],
        treatment: ['生活方式改变', 'ACE抑制剂', '钙通道阻滞剂', '利尿剂'],
        prevention: ['健康饮食', '规律运动', '戒烟限酒', '控制体重', '减少压力'],
        prognosis: '通过适当治疗可以控制，但需要长期管理',
        relatedDiseases: ['冠心病', '脑卒中', '肾病', '眼底病变']
      },
      {
        name: '糖尿病',
        icdCode: 'E11',
        description: '以高血糖为主要特征的代谢性疾病群',
        symptoms: ['多饮', '多尿', '多食', '体重减轻', '乏力'],
        causes: ['胰岛素分泌不足', '胰岛素抵抗', '遗传因素'],
        riskFactors: ['肥胖', '家族史', '年龄', '缺乏运动', '高血压'],
        diagnosis: ['血糖检测', '糖化血红蛋白', '糖耐量试验'],
        treatment: ['饮食控制', '运动疗法', '药物治疗', '胰岛素治疗'],
        prevention: ['健康饮食', '规律运动', '控制体重', '定期体检'],
        prognosis: '通过综合管理可以控制病情，预防并发症',
        relatedDiseases: ['糖尿病肾病', '糖尿病眼病', '糖尿病足', '冠心病']
      }
    ]

    diseasesData.forEach(disease => {
      this.diseases.set(disease.name, disease)
      if (disease.icdCode) {
        this.diseases.set(disease.icdCode, disease)
      }
    })
  }

  /**
   * 加载诊断检查信息
   */
  private loadDiagnosticTests() {
    const testsData: DiagnosticTest[] = [
      {
        name: '血常规',
        type: 'blood',
        description: '检查血液中各种细胞的数量和形态',
        indications: ['感染诊断', '贫血检查', '血液疾病筛查', '健康体检'],
        preparation: ['空腹不是必需的', '避免剧烈运动', '充分休息'],
        procedure: '静脉采血，通常从肘部静脉抽取2-5ml血液',
        normalRanges: {
          '白细胞': '4.0-10.0×10^9/L',
          '红细胞': '男4.0-5.5，女3.5-5.0×10^12/L',
          '血红蛋白': '男120-160，女110-150g/L',
          '血小板': '100-300×10^9/L'
        },
        interpretation: ['白细胞增高提示感染', '红细胞减少提示贫血', '血小板减少注意出血风险'],
        risks: ['轻微疼痛', '局部血肿', '感染（极罕见）'],
        cost: 50
      },
      {
        name: '心电图',
        type: 'physical',
        description: '记录心脏电活动的检查',
        indications: ['胸痛', '心悸', '心律不齐', '术前检查'],
        preparation: ['穿着方便的衣服', '去除金属饰品', '保持安静'],
        procedure: '在胸部和四肢贴电极，记录心电波形',
        interpretation: ['心律', '心率', '传导', 'ST段变化'],
        risks: ['无创检查', '无辐射', '非常安全'],
        cost: 30
      }
    ]

    testsData.forEach(test => {
      this.diagnosticTests.set(test.name, test)
    })
  }

  /**
   * 加载科室专科信息
   */
  private loadDepartments() {
    const departmentsData: DepartmentSpecialty[] = [
      {
        name: '心内科',
        description: '专门诊治心血管系统疾病的科室',
        commonConditions: ['高血压', '冠心病', '心律失常', '心力衰竭', '心肌病'],
        procedures: ['心电图', '心脏彩超', '冠状动脉造影', '心导管检查'],
        specialists: ['心内科医师', '介入心脏病学专家'],
        equipment: ['心电图机', '心脏彩超', '动态心电图', '运动平板'],
        whenToVisit: ['胸痛', '心悸', '气短', '高血压', '心律不齐'],
        preparationTips: ['带齐病历', '空腹检查', '穿方便的衣服', '避免剧烈运动']
      },
      {
        name: '消化内科',
        description: '专门诊治消化系统疾病的科室',
        commonConditions: ['胃炎', '消化性溃疡', '肝炎', '胆囊炎', '肠炎'],
        procedures: ['胃镜', '肠镜', '肝功能检查', '腹部超声'],
        specialists: ['消化内科医师', '内镜专家'],
        equipment: ['胃镜', '肠镜', '超声设备'],
        whenToVisit: ['腹痛', '恶心呕吐', '腹泻', '便血', '黄疸'],
        preparationTips: ['检查前禁食', '停用影响检查的药物', '了解检查流程']
      }
    ]

    departmentsData.forEach(dept => {
      this.departments.set(dept.name, dept)
    })
  }

  /**
   * 加载急诊关键词
   */
  private loadEmergencyKeywords() {
    const emergencyWords = [
      '胸痛', '呼吸困难', '意识丧失', '大出血', '剧烈头痛',
      '高热不退', '严重外伤', '中毒', '窒息', '休克',
      '心悸', '晕厥', '抽搐', '呕血', '便血'
    ]

    emergencyWords.forEach(word => {
      this.emergencyKeywords.add(word)
    })
  }

  /**
   * 症状分析
   */
  analyzeSymptom(symptom: string): SymptomInfo | null {
    return this.symptoms.get(symptom) || null
  }

  /**
   * 多症状联合分析
   */
  analyzeMultipleSymptoms(symptoms: string[]): {
    possibleConditions: string[]
    recommendedDepartment: string
    urgencyLevel: 'low' | 'medium' | 'high' | 'critical'
    recommendations: string[]
  } {
    const symptomInfos = symptoms.map(s => this.symptoms.get(s)).filter(Boolean) as SymptomInfo[]
    
    if (symptomInfos.length === 0) {
      return {
        possibleConditions: [],
        recommendedDepartment: '内科',
        urgencyLevel: 'low',
        recommendations: ['请咨询医生获得准确诊断']
      }
    }

    // 分析紧急程度
    let maxUrgency: 'low' | 'medium' | 'high' | 'critical' = 'low'
    const urgencyLevels = { low: 1, medium: 2, high: 3, critical: 4 }
    
    symptomInfos.forEach(info => {
      if (urgencyLevels[info.urgencyLevel] > urgencyLevels[maxUrgency]) {
        maxUrgency = info.urgencyLevel
      }
    })

    // 推荐科室（取最常见的）
    const deptCounts: Record<string, number> = {}
    symptomInfos.forEach(info => {
      info.recommendedDepartments.forEach(dept => {
        deptCounts[dept] = (deptCounts[dept] || 0) + 1
      })
    })

    const recommendedDepartment = Object.keys(deptCounts).reduce((a, b) => 
      deptCounts[a] > deptCounts[b] ? a : b
    ) || '内科'

    // 可能的疾病（基于症状组合）
    const possibleConditions = this.identifyPossibleConditions(symptoms)

    // 综合建议
    const recommendations = this.generateRecommendations(symptomInfos, maxUrgency)

    return {
      possibleConditions,
      recommendedDepartment,
      urgencyLevel: maxUrgency,
      recommendations
    }
  }

  /**
   * 药物查询
   */
  getMedicationInfo(medicationName: string): MedicationInfo | null {
    return this.medications.get(medicationName) || this.medications.get(medicationName.toLowerCase()) || null
  }

  /**
   * 药物相互作用检查
   */
  checkDrugInteractions(medications: string[]): {
    interactions: Array<{
      drug1: string
      drug2: string
      severity: 'mild' | 'moderate' | 'severe'
      description: string
    }>
    warnings: string[]
  } {
    const interactions: any[] = []
    const warnings: string[] = []

    // 简化的药物相互作用检查
    for (let i = 0; i < medications.length; i++) {
      for (let j = i + 1; j < medications.length; j++) {
        const med1 = this.medications.get(medications[i])
        const med2 = this.medications.get(medications[j])

        if (med1 && med2) {
          // 检查是否有已知的相互作用
          const hasInteraction = med1.interactions.some(interaction => 
            medications[j].toLowerCase().includes(interaction.toLowerCase())
          )

          if (hasInteraction) {
            interactions.push({
              drug1: medications[i],
              drug2: medications[j],
              severity: 'moderate',
              description: '可能存在相互作用，请咨询医师'
            })
          }
        }
      }
    }

    if (interactions.length > 0) {
      warnings.push('发现潜在的药物相互作用，请咨询医师或药师')
    }

    return { interactions, warnings }
  }

  /**
   * 疾病信息查询
   */
  getDiseaseInfo(diseaseName: string): DiseaseInfo | null {
    return this.diseases.get(diseaseName) || null
  }

  /**
   * 检查项目信息
   */
  getDiagnosticTestInfo(testName: string): DiagnosticTest | null {
    return this.diagnosticTests.get(testName) || null
  }

  /**
   * 科室信息查询
   */
  getDepartmentInfo(deptName: string): DepartmentSpecialty | null {
    return this.departments.get(deptName) || null
  }

  /**
   * 急诊判断
   */
  isEmergency(symptoms: string[], description?: string): {
    isEmergency: boolean
    urgencyLevel: 'low' | 'medium' | 'high' | 'critical'
    reasons: string[]
    recommendations: string[]
  } {
    let isEmergency = false
    let urgencyLevel: 'low' | 'medium' | 'high' | 'critical' = 'low'
    const reasons: string[] = []
    const recommendations: string[] = []

    // 检查急诊关键词
    const emergencySymptoms = symptoms.filter(s => this.emergencyKeywords.has(s))
    if (emergencySymptoms.length > 0) {
      isEmergency = true
      urgencyLevel = 'critical'
      reasons.push(`发现急诊症状: ${emergencySymptoms.join(', ')}`)
      recommendations.push('建议立即前往急诊科就诊')
    }

    // 检查症状组合的严重程度
    const analysis = this.analyzeMultipleSymptoms(symptoms)
    if (analysis.urgencyLevel === 'critical' || analysis.urgencyLevel === 'high') {
      isEmergency = true
      urgencyLevel = analysis.urgencyLevel
      reasons.push('症状组合提示可能的严重疾病')
      recommendations.push(`建议前往${analysis.recommendedDepartment}或急诊科`)
    }

    // 分析描述文本中的紧急指标
    if (description) {
      const emergencyPhrases = ['剧烈', '严重', '突然', '无法忍受', '急性', '大量']
      const hasEmergencyPhrase = emergencyPhrases.some(phrase => description.includes(phrase))
      if (hasEmergencyPhrase) {
        if (urgencyLevel === 'low') urgencyLevel = 'high'
        reasons.push('症状描述提示紧急情况')
        recommendations.push('建议及时就医')
      }
    }

    return {
      isEmergency,
      urgencyLevel,
      reasons,
      recommendations
    }
  }

  /**
   * 生成医疗建议
   */
  generateMedicalAdvice(query: {
    symptoms?: string[]
    medications?: string[]
    conditions?: string[]
    age?: number
    gender?: 'male' | 'female'
  }): {
    advice: string[]
    warnings: string[]
    nextSteps: string[]
    resources: string[]
  } {
    const advice: string[] = []
    const warnings: string[] = []
    const nextSteps: string[] = []
    const resources: string[] = []

    // 症状建议
    if (query.symptoms && query.symptoms.length > 0) {
      const analysis = this.analyzeMultipleSymptoms(query.symptoms)
      advice.push(`建议就诊科室: ${analysis.recommendedDepartment}`)
      
      if (analysis.urgencyLevel === 'critical' || analysis.urgencyLevel === 'high') {
        warnings.push('症状可能提示严重疾病，请及时就医')
        nextSteps.push('立即预约或前往急诊科')
      } else {
        nextSteps.push('可预约门诊时间就诊')
      }
    }

    // 药物建议
    if (query.medications && query.medications.length > 0) {
      const interactions = this.checkDrugInteractions(query.medications)
      if (interactions.interactions.length > 0) {
        warnings.push('发现潜在药物相互作用')
        nextSteps.push('咨询医师或药师确认用药安全性')
      }
    }

    // 资源推荐
    resources.push('可通过医院官网或APP预约挂号')
    resources.push('24小时急诊科开放')
    resources.push('药物咨询可联系医院药房')

    return { advice, warnings, nextSteps, resources }
  }

  /**
   * 智能问诊
   */
  conductIntelligentConsultation(userInputs: {
    chiefComplaint: string
    symptoms: string[]
    duration: string
    severity: number // 1-10
    additionalInfo?: string
  }): {
    preliminaryAssessment: string
    suggestedDepartment: string
    urgencyLevel: 'low' | 'medium' | 'high' | 'critical'
    recommendedActions: string[]
    followUpQuestions: string[]
  } {
    const { chiefComplaint, symptoms, duration, severity } = userInputs

    // 分析症状
    const analysis = this.analyzeMultipleSymptoms(symptoms)
    
    // 考虑严重程度和持续时间
    let adjustedUrgency = analysis.urgencyLevel
    if (severity >= 8) {
      adjustedUrgency = adjustedUrgency === 'low' ? 'medium' : 
                       adjustedUrgency === 'medium' ? 'high' : 'critical'
    }

    // 生成初步评估
    let preliminaryAssessment = `基于您描述的症状 "${chiefComplaint}" 和相关症状，`
    
    if (analysis.possibleConditions.length > 0) {
      preliminaryAssessment += `可能涉及: ${analysis.possibleConditions.slice(0, 3).join(', ')}。`
    }

    preliminaryAssessment += `建议${adjustedUrgency === 'critical' ? '立即' : adjustedUrgency === 'high' ? '尽快' : '适时'}就医。`

    // 推荐行动
    const recommendedActions: string[] = []
    switch (adjustedUrgency) {
      case 'critical':
        recommendedActions.push('立即前往急诊科')
        recommendedActions.push('如需要可拨打120')
        break
      case 'high':
        recommendedActions.push('当日预约就诊')
        recommendedActions.push('观察症状变化')
        break
      case 'medium':
        recommendedActions.push('1-3天内预约就诊')
        recommendedActions.push('注意休息，避免劳累')
        break
      default:
        recommendedActions.push('可预约常规门诊')
        recommendedActions.push('保持健康生活方式')
    }

    // 后续问题
    const followUpQuestions = this.generateFollowUpQuestions(symptoms, analysis)

    return {
      preliminaryAssessment,
      suggestedDepartment: analysis.recommendedDepartment,
      urgencyLevel: adjustedUrgency,
      recommendedActions,
      followUpQuestions
    }
  }

  // 辅助方法
  private identifyPossibleConditions(symptoms: string[]): string[] {
    // 基于症状组合识别可能的疾病
    const conditions: string[] = []

    if (symptoms.includes('胸痛') && symptoms.includes('呼吸困难')) {
      conditions.push('心肌梗死', '肺栓塞', '气胸')
    }

    if (symptoms.includes('头痛') && symptoms.includes('发热')) {
      conditions.push('脑膜炎', '脑炎', '感染性疾病')
    }

    if (symptoms.includes('腹痛') && symptoms.includes('恶心')) {
      conditions.push('急性胃肠炎', '阑尾炎', '胆囊炎')
    }

    return conditions
  }

  private generateRecommendations(symptoms: SymptomInfo[], urgency: string): string[] {
    const recommendations: string[] = []

    if (urgency === 'critical') {
      recommendations.push('立即就医，不要延误')
      recommendations.push('可考虑拨打急救电话')
    } else if (urgency === 'high') {
      recommendations.push('尽快就医，当日预约')
      recommendations.push('密切观察症状变化')
    } else {
      recommendations.push('建议就医检查')
      recommendations.push('保持充分休息')
    }

    // 添加通用建议
    recommendations.push('保持充分水分摄入')
    recommendations.push('避免自行用药')
    recommendations.push('记录症状变化')

    return recommendations
  }

  private generateFollowUpQuestions(symptoms: string[], analysis: any): string[] {
    const questions: string[] = []

    questions.push('症状是突然出现的还是逐渐加重的？')
    questions.push('是否有诱发因素？')
    questions.push('之前是否有类似症状？')
    questions.push('目前是否在服用任何药物？')
    questions.push('是否有相关的家族病史？')

    // 基于特定症状的问题
    if (symptoms.includes('头痛')) {
      questions.push('头痛的性质是胀痛、刺痛还是搏动性？')
    }

    if (symptoms.includes('胸痛')) {
      questions.push('疼痛是否向其他部位放射？')
    }

    return questions.slice(0, 5) // 限制问题数量
  }
}

// 导出单例实例
export const medicalKnowledge = new MedicalKnowledge()

// 导出快捷方法
export const analyzeSymptom = (symptom: string) => medicalKnowledge.analyzeSymptom(symptom)
export const analyzeMultipleSymptoms = (symptoms: string[]) => medicalKnowledge.analyzeMultipleSymptoms(symptoms)
export const getMedicationInfo = (name: string) => medicalKnowledge.getMedicationInfo(name)
export const checkDrugInteractions = (medications: string[]) => medicalKnowledge.checkDrugInteractions(medications)
export const isEmergency = (symptoms: string[], description?: string) => medicalKnowledge.isEmergency(symptoms, description)

export default medicalKnowledge